package com.example.xinhuazidian

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.azhon.appupdate.manager.DownloadManager
import com.example.xinhuazidian.base.AboutPrensenter
import com.example.xinhuazidian.base.AboutView
import com.example.xinhuazidian.base.BaseActivity
import com.example.xinhuazidian.bean.LatestBean
import com.example.xinhuazidian.databinding.ActivityAboutBinding
import com.example.xinhuazidian.utils.AppVersionNameAndCode
import com.example.xinhuazidian.utils.LoadingDialog
import com.example.xinhuazidian.utils.OneClickThree
import com.gyf.immersionbar.ImmersionBar

/**
 * 关于
 */
class AboutActivity : BaseActivity<AboutPrensenter>(), View.OnClickListener, AboutView {

    private lateinit var binding: ActivityAboutBinding
    private val REQUEST_SD = 200
    private val REQUEST_SHARE = 202
    private var loadingDialog: LoadingDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAboutBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initView()
        initData()
    }

    private fun initView() {
        //沉浸状态栏
        ImmersionBar.with(this)
            .statusBarDarkFont(true)//状态栏字体是深色，不写默认为亮色
            .init()

        binding.rlUpdates.setOnClickListener(this)
        binding.rlShare.setOnClickListener(this)
        loadingDialog = LoadingDialog(this@AboutActivity, "")
    }

    @SuppressLint("SetTextI18n")
    private fun initData() {
        binding.tvCode.text = "${AppVersionNameAndCode.getVersionName(this)}(${
            AppVersionNameAndCode.getVersionCode(this)
        })"
    }

    private fun share() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                REQUEST_SHARE
            )
        } else {
            shareImg(BitmapFactory.decodeResource(resources, R.drawable.icon_qr_code))
        }
    }

    /**
     * 分享图片(直接将bitamp转换为Uri)
     */
    private fun shareImg(bitmap: Bitmap) {
        val uri: Uri =
            Uri.parse(MediaStore.Images.Media.insertImage(contentResolver, bitmap, null, null))
        var intent = Intent()
        intent.action = Intent.ACTION_SEND
        intent.type = "image/*" //设置分享内容的类型
        intent.putExtra(Intent.EXTRA_STREAM, uri)
        intent = Intent.createChooser(intent, resources.getString(R.string.app_name))
        startActivity(intent)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_SD) {
            updata()
        } else if (requestCode == REQUEST_SHARE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                shareImg(BitmapFactory.decodeResource(resources, R.drawable.icon_qr_code))
            } else {
                Toast.makeText(
                    this,
                    "你拒绝了权限申请，可能无法进行下面的操作哦",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    override fun createPresenter(): AboutPrensenter {
        return AboutPrensenter(this)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.rlUpdates -> {
                if (!OneClickThree.isFastClick) {
                    loadingDialog?.show()
                    presenter?.latest(
                        "6414498df945486bdb5242b5",
                        "6570963ae9a308ca993393518f865887"
                    )
                }
            }

            R.id.rlShare -> {
                share()//分享
            }
        }
    }

    private var updataBean: LatestBean? = null
    private var string: String? = null

    override fun latestData(bean: LatestBean?) {
        loadingDialog?.dismiss()
        if (bean != null) {
            string = bean.direct_install_url
            updataBean = bean
            updata()
        }
    }

    private fun updata() {
        if (AppVersionNameAndCode.getVersionCode(this@AboutActivity) < updataBean!!.build!!.toInt()) {
            val manager = DownloadManager.Builder(this).run {
                apkUrl(string!!)
                apkName("xinhuazidian.apk")
                smallIcon(R.mipmap.ic_launcher)
                //设置了此参数，那么内部会自动判断是否需要显示更新对话框，否则需要自己判断是否需要更新
                apkVersionCode(updataBean!!.build!!.toInt())
                //同时下面三个参数也必须要设置
                apkVersionName(updataBean!!.versionShort!!)
                apkSize((updataBean!!.binary!!.fsize / 1024 / 1024).toString() + "." + updataBean!!.binary!!.fsize / 1024 % 1024 + "M")
                apkDescription(updataBean!!.changelog!!)
                //省略一些非必须参数...
                build()
            }
            manager.download()
        } else {
            Toast.makeText(this, "已是最新版本", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onError(msg: String?) {
        loadingDialog?.dismiss()
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }
}